//
//  ImageViewController.m
//  Systetagram
//
//  Created by 欧杨 on 2021/1/5.
//

#import "AppDelegate.h"
#import "ImageViewController.h"
#import "ProfileViewController.h"
#import "userModel.h"
#import <Masonry.h>
#import <AFNetworking.h>
#import <Photos/Photos.h>

@interface ImageViewController ()

@end

@implementation ImageViewController

- (instancetype)initWithBlogModel:(blogModel *)model andImage:(nonnull UIImage *)image
{
    self = [super init];
    if (self) {
        self.image = image;
        self.model = model;
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.image = [UIImage imageNamed:@"long"];
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.blackColor;
    
    [self layoutViews];
}

- (UIScrollView *)imageView
{
    if (!_imageView) {
        _imageView = [[UIScrollView alloc] init];
        _imageView.showsVerticalScrollIndicator = NO;
        CGFloat imageW = self.view.bounds.size.width;
        CGFloat imageH = imageW * _image.size.height / _image.size.width;
        _imageView.contentSize = CGSizeMake(0, imageH);
        UIImageView *imagev = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageW, imageH)];
        imagev.image = _image;
        [_imageView addSubview:imagev];
    }
    return _imageView;
}

- (UIImageView *)profilePic
{
    if (!_profilePic) {
        _profilePic = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
        _profilePic.backgroundColor = UIColor.whiteColor;
        _profilePic.userInteractionEnabled = YES;
        _profilePic.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarClicked)];
        [_profilePic addGestureRecognizer:singleGesture];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        NSString *URLString = @"http://47.107.247.52:8080/user";
        NSDictionary *parameters = @{@"id":self.model.user_id};
        [manager POST:URLString parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"ok"] boolValue]) {
                userModel *user = [[userModel alloc] initWithDictionary:((NSDictionary *)responseObject)[@"data"]];
                NSString *url = [NSString stringWithFormat:@"%@%@",@"http://47.107.247.52:8080/", user.avatar];
                NSURL *imageURL = [NSURL URLWithString:url];
                NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithURL:imageURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                    if (error == nil) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            self.profilePic.image = [UIImage imageWithData:data];
                        });
                    }
                }];
                [task resume];
            } else {
                NSLog(@"something wrong when get profile");
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
        }];
    }
    return _profilePic;
}

- (UILabel *)nickName
{
    if (!_nickName) {
        _nickName = [[UILabel alloc] init];
        _nickName.text = self.model.username;
        _nickName.textColor = UIColor.whiteColor;
        _nickName.font = [_nickName.font fontWithSize:32];
    }
    return _nickName;
}

- (UILabel *)publishDate
{
    if (!_publishDate) {
        _publishDate = [[UILabel alloc] init];
        _publishDate.textColor = UIColor.whiteColor;
    }
    return _publishDate;
}

- (DOFavoriteButton *)like
{
    if (!_like) {
        AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        _like = [[DOFavoriteButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        [_like addTarget:self action:@selector(likeClicked:) forControlEvents:UIControlEventTouchUpInside];
        _like.image = [UIImage imageNamed:@"like"];
        _like.imageColorOff = UIColor.whiteColor;
        _like.imageColorOn = UIColor.redColor;
        _like.circleColor = UIColor.whiteColor;
        _like.lineColor = UIColor.whiteColor;
        _like.duration = 1;
        _like.selected = [myDelegate.likeList containsObject:self.model];
    }
    return _like;
}

- (UILabel *)likeNum
{
    if (!_likeNum) {
        _likeNum = [[UILabel alloc] init];
        _likeNum.text = self.model.good_num.stringValue;
        _likeNum.textColor = UIColor.whiteColor;
        _likeNum.font = [_likeNum.font fontWithSize:32];
    }
    return _likeNum;
}

- (UIButton *)download
{
    if (!_download) {
        _download = [UIButton buttonWithType:UIButtonTypeCustom];
        _download.tintColor = UIColor.whiteColor;
        [_download setImage:[[UIImage imageNamed:@"download"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        [_download addTarget:self action:@selector(downloadClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _download;
}

-(void)layoutViews
{
    [self.view addSubview:self.imageView];
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-200);
    }];
    
    [self.view addSubview:self.profilePic];
    [_profilePic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(80);
        make.left.equalTo(self.view).mas_offset(10);
        make.top.equalTo(_imageView.mas_bottom).mas_offset(10);
    }];
    
    [self.view addSubview:self.nickName];
    [_nickName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_profilePic.mas_right).mas_offset(5);
        make.top.equalTo(_profilePic).mas_offset(10);
    }];
    
    [self.view addSubview:self.like];
    [_like mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(44);
        make.top.equalTo(_imageView.mas_bottom).mas_offset(10);
        make.right.equalTo(self.view.mas_right).mas_offset(-10);
    }];
    
    [self.view addSubview:self.likeNum];
    [_likeNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_like.mas_bottom).mas_offset(10);
        make.centerX.equalTo(_like);
    }];
    
    [self.view addSubview:self.download];
    [_download mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(44, 44));
        make.right.equalTo(_like.mas_left).offset(-20);
        make.centerY.equalTo(_like);
    }];
}

-(void)avatarClicked
{
    NSLog(@"avatar clicked");
    ProfileViewController *VC = [[ProfileViewController alloc] initWithUserID:self.model.user_id];
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)likeClicked:(id)sender
{
    AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    if (((DOFavoriteButton *)sender).selected) {
        [sender deselect];
        self.model.good_num = @([self.model.good_num unsignedLongValue]-1);
        self.likeNum.text = self.model.good_num.stringValue;
        //[myDelegate.likeList removeObject:<#(nonnull id)#>]
        NSLog(@"deselected");
        NSString *URLString = [NSString stringWithFormat:@"%@%@%@", @"http://47.107.247.52:8080/user/", myDelegate.userID, @"/dislike"];
        NSDictionary *parameters = @{@"user_id":myDelegate.userID, @"blog_id":self.model.ID};
        NSDictionary *header = @{@"token":myDelegate.token};
//        [manager POST:URLString parameters:parameters headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            if ([responseObject[@"ok"] boolValue]) {
//                [sender deselect];
//                self.model.good_num = @([self.model.good_num unsignedLongValue]-1);
//                self.likeNum.text = self.model.good_num.stringValue;
//                //[myDelegate.likeList removeObject:<#(nonnull id)#>]
//                NSLog(@"deselected");
//            } else {
//                NSLog(@"something wrong when dislike");
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"%@", error);
//        }];
    } else {
        self.model.good_num = @([self.model.good_num unsignedLongValue]+1);
        self.likeNum.text = self.model.good_num.stringValue;
        [myDelegate.likeList addObject:self.model];
        NSLog(@"selected");
        [sender select];
        
        NSString *URLString = [NSString stringWithFormat:@"%@%@%@", @"http://47.107.247.52:8080/user/", myDelegate.userID, @"/like"];
        NSDictionary *parameters = @{@"user_id":myDelegate.userID, @"blog_id":self.model.ID};
        NSDictionary *header = @{@"token":myDelegate.token};
//        [manager POST:URLString parameters:parameters headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            if ([responseObject[@"ok"] boolValue]) {
//                self.model.good_num = @([self.model.good_num unsignedLongValue]+1);
//                self.likeNum.text = self.model.good_num.stringValue;
//                [myDelegate.likeList addObject:self.model];
//                NSLog(@"selected");
//                [sender select];
//            } else {
//                NSLog(@"something wrong when like");
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"%@", error);
//        }];
    }
}

-(void)downloadClicked
{
    PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
    [library performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"保存照片到本地"
                                                                           message:[NSString stringWithFormat:@"保存失败\n原因：%@", error]
                                           preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel
               handler:^(UIAlertAction * action) {
            }];
            [alert addAction:confirmAction];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:alert animated:YES completion:nil];
            });
        } else {
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"保存照片到本地"
                                           message:@"保存成功"
                                           preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel
               handler:^(UIAlertAction * action) {
            }];
            [alert addAction:confirmAction];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:alert animated:YES completion:nil];
            });
        }
    }];
}

@end
